package cn.bonoon.kernel.expression;

import java.util.HashMap;
import java.util.Map;

import org.springframework.util.Assert;

import cn.bonoon.kernel.annotations.QueryExpression;
import cn.bonoon.kernel.annotations.QueryJoin;
import cn.bonoon.kernel.expression.results.RequestExpressionValue;

/**
 * 只解析where部分，并且是动态解析的，即如果有表达式，都可以加进来
 * @author jackson
 *
 */
public class WhereExpressionWrapper extends AbstractExpressionWrapper implements ExpressionParseContext, QueryConditionExpressionParser{
	
	private Map<String, String> joinMapped;
	
	@Override
	protected void internalParse(String query, ExpressionPropertyResolver expressionResolver)throws Exception{
		append(" and(");
		super.internalParse(query, expressionResolver);
		append(')');
	}
	
	private void internalAdd(ExpressionPropertyResolver propertyResolver, QueryExpression expression) throws Exception{
		if(expression.joins().length > 0){
			if(null == joinMapped) joinMapped = new HashMap<>();
			
			for(QueryJoin je : expression.joins()){
				joinMapped.put(je.value(), je.alias());
			}
		}
		internalParse(expression.value(), propertyResolver);
	}

	public void add(QueryExpression expression) throws Exception{
		internalAdd(defaultPropertyResolver(), expression);
	}

	public void add(ExpressionPropertyResolver propertyResolver, QueryExpression expression) throws Exception{
		internalAdd(propertyResolver, expression);
	}

	public void add(ExpressionPropertyResolver propertyResolver, QueryExpression... expressions) throws Exception{
		for(QueryExpression expression : expressions){
			internalAdd(propertyResolver, expression);
		}
	}

	public void add(String expression) throws Exception{
		Assert.notNull(expression, "表达式不允许为空！");
		internalParse(expression, defaultPropertyResolver());
	}

	public void add(String expression, String value) throws Exception{
		Assert.notNull(expression, "表达式不允许为空！");
		append(" and ", expression);
		
		value(new RequestExpressionValue(this, value, "J"));
		parameter(new QueryExpressionParameter(value, value, QueryExpressionParameterMode.INPUT));
	}

	public void and(String exp) {
		append(" and ", exp);
	}

	public void or(String exp) {
		append(" or(", exp, ")");
	}

	@Override
	public Map<String, String> joinMapped() {
		return joinMapped;
	}

	@Override
	public String where() {
		return toString();
	}
}
